﻿#include "websocketnetworkcenter.h"

#include <QUuid>
#include <qglobalconfig.h>

QMutex WebSocketNetWorkCenter::mutex;
WebSocketNetWorkCenter* WebSocketNetWorkCenter::instance = nullptr;

WebSocketNetWorkCenter *WebSocketNetWorkCenter::getInstance()
{
    if (instance == nullptr) {
        QMutexLocker locker(&mutex);
        if (instance == nullptr) {
            instance = new WebSocketNetWorkCenter();
        }
    }
    return instance;
}

void WebSocketNetWorkCenter::deleteInstance()
{
    if (instance != nullptr) {
        delete instance;
        instance = nullptr;
    }
}

void WebSocketNetWorkCenter::sendMessage(QString &message)
{
    signal_send_message(message);
}

WebSocketNetWorkCenter::WebSocketNetWorkCenter(QObject *parent) : QThread(parent)
{
    qDebug() << __FUNCTION__;
    moveToThread(this); // 确保对象在自己的线程中运行
    qRegisterMetaType<QWebSocket*>("QWebSocket*");
    connect(this,&WebSocketNetWorkCenter::signal_send_message,this,&WebSocketNetWorkCenter::slot_send_message,Qt::BlockingQueuedConnection);
    start();
}

WebSocketNetWorkCenter::~WebSocketNetWorkCenter()
{
    quit();
    wait();
    qDebug() << __FUNCTION__;
}

void WebSocketNetWorkCenter::slot_send_message(QString &message)
{
    QMutexLocker locker(&clientMapMutex);

    for(auto *socket : clientMap){
        if(socket->bytesToWrite() < 65536){
            socket->sendTextMessage(message);
        }
    }
}

void WebSocketNetWorkCenter::handleNewConnection()
{
    QMutexLocker locket(&clientMapMutex);
    QWebSocket *pClient = m_server->nextPendingConnection();
    QString key = QUuid::createUuid().toString(); // 使用UUID作为每个连接的唯一标识符
    pClient->setProperty("connectKey",key);
    clientMap.insert(key, pClient);
    qDebug() << __FUNCTION__ << "WebSocket Connection insert:" << pClient->property("connectKey").toString();
//    connect(pClient, &QWebSocket::textMessageReceived, this, &SpectrumSituationWebSocketServer::processTextMessage);
    connect(pClient, &QWebSocket::disconnected, this, &WebSocketNetWorkCenter::onSocketDisconnected);
}

void WebSocketNetWorkCenter::onSocketDisconnected()
{
    QMutexLocker locker(&clientMapMutex);

    QWebSocket *pClient = qobject_cast<QWebSocket *>(sender());
    if (pClient) {
        clientMap.remove(pClient->property("connectKey").toString());
        qDebug()<< __FUNCTION__ << "WebSocket Connection removed:" << pClient->property("connectKey").toString();
        pClient->deleteLater();// 安全地删除客户端对象
    }
}

void WebSocketNetWorkCenter::run()
{
    QString listenAdderss = QGlobalConfig::getInstance().read("websocket","listenAdderss","127.0.0.1").toString();
    quint16 listenPort = QGlobalConfig::getInstance().read("websocket","listenPort",3811).toUInt();
    m_server = new QWebSocketServer(QStringLiteral("SpectrumSituation WebSocket Server"), QWebSocketServer::NonSecureMode,this);
    if (m_server->listen(QHostAddress::AnyIPv4, listenPort)) {
        QHostAddress serverAddress = m_server->serverAddress();
        qDebug() << __FUNCTION__  << QString("WebSocket server listening on address:%1 port:%2").arg(serverAddress.toString()).arg(listenPort) << "in thread" << QThread::currentThreadId();
        connect(m_server, &QWebSocketServer::newConnection, this, &WebSocketNetWorkCenter::handleNewConnection);
    } else {
        qDebug() << "Failed to start WebSocket server";
    }
    exec(); // 进入事件循环，等待处理新连接
    m_server->close();
    delete m_server;
}
